<template>
  <div class="app-container">
    <!-- 工具栏 -->
    <div class="head-container">
      <div>
        <!-- 搜索 -->
        <el-input
          v-model="query.appNub"
          size="small"
          clearable
          placeholder="输入申请编号"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleSearch"
        />
        <el-select
          v-model="query.appDept"
          size="small"
          clearable
          placeholder="输入申请单位"
          style="width: 160px;"
          class="filter-item"
        >
          <el-option v-for="item in appDeptOptions" :key="item.id" :label="item.label" :value="item.value" />

        </el-select>
        <el-input
          v-model="query.appName"
          size="small"
          clearable
          placeholder="选择申请人"
          style="width: 160px;"
          class="filter-item"
        />
        <el-select
          v-model="query.appStu"
          size="small"
          clearable
          placeholder="选择申请状态"
          style="width: 160px;"
          class="filter-item"
        >
          <el-option label="待审批" value="0" />
          <el-option label="数据局审批通过" value="1" />
          <el-option label="审批通过" value="2" />
          <el-option label="审批拒绝" value="3" />
          <el-option label="已撤销" value="4" />
        </el-select>
        <el-select
          v-model="query.isMr"
          size="small"
          clearable
          placeholder="是否挂载资源"
          style="width: 160px;"
          class="filter-item"
        >
          <el-option label="是" value="0" />
          <el-option label="否" value="1" />
        </el-select>
        <el-date-picker
          v-model="timeValue"
          class="filter-item"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        />
        <el-button size="small" type="primary" class="filter-item" @click="handleSearch">
          搜索
        </el-button>
        <el-button size="small" class="filter-item" @click="resetSearch">
          重置
        </el-button>
      </div>
    </div>
    <!-- 表格区域 -->
    <div slot="header" class="clearfix">
      <span class="role-span">申请列表</span>
    </div>
    <el-table v-loading="loading" highlight-current-row style="width: 100%;margin-top: 10px" :data="tableData" border>
      <!-- 所有字段均已添加到表格中 -->
      <el-table-column prop="appNub" label="申请编号" width="140" />
      <el-table-column prop="catalogName" label="编目名称" width="180" />
      <el-table-column label="资源类型" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.appMethod === '0'">API</span>
          <span v-if="scope.row.appMethod === '1'">数据库</span>
          <span v-if="scope.row.appMethod === '2'">文件</span>
        </template>
      </el-table-column>
      <el-table-column prop="appDept" label="申请单位" width="140" />
      <el-table-column prop="appName" label="申请人姓名" width="120" />
      <el-table-column prop="appPhone" label="申请人电话" width="130" />
      <el-table-column prop="appEmail" label="申请人邮箱" width="180" />
      <el-table-column prop="createTime" label="申请时间" width="180" />
      <el-table-column prop="appScenarios" label="应用场景" width="160" show-overflow-tooltip />
      <el-table-column prop="appMatters" label="应用事项" width="140" show-overflow-tooltip />
      <el-table-column prop="appBasis" label="申请依据" width="140" show-overflow-tooltip />
      <el-table-column label="申请状态" width="140">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.appStu)">
            {{ getStatusText(scope.row.appStu) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" width="140" show-overflow-tooltip />
      <el-table-column label="是否超期" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.isOverdue === 0" class="text-success">是</span>
          <span v-if="scope.row.isOverdue === 1" class="text-danger">否</span>
        </template>
      </el-table-column>
      <el-table-column label="是否挂载资源" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.isMr === 0" class="text-success">是</span>
          <span v-if="scope.row.isMr === 1" class="text-danger">否</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="400px" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-view" @click="openDetailDialog(scope.row)">查看
          </el-button>
          <!-- 根据申请状态判断是否显示挂载按钮且控制是否可点击 -->
          <el-button
            size="mini"
            type="success"
            icon="el-icon-upload"
            :disabled="(!(scope.row.appStu == '2' && scope.row.isMr == 1) )|| scope.row.appStu == '5'"
            @click="mountResource(scope.row)"
          >挂载
          </el-button>
          <!-- 根据申请状态判断是否显示解除挂载按钮且控制是否可点击 -->
          <el-button
            size="mini"
            type="warning"
            icon="el-icon-download"
            :disabled="scope.row.appStu !== '2' || scope.row.isMr === 1 || scope.row.appStu == '5'"
            @click="unmountResource(scope.row)"
          >解除挂载
          </el-button>
          <el-button type="danger" icon="el-icon-delete" :disabled="scope.row.appStu == '5'" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-container">
      <!--      <el-pagination-->
      <!--        background-->
      <!--        layout="prev, pager, next, total"-->
      <!--        :total="totalCount"-->
      <!--        :page-size="pageSize"-->
      <!--        :current-page="currentPage"-->
      <!--        @current-change="changePage"-->
      <!--      />-->
      <Pagination
        :total-num="totalCount"
        :current-page="currentPage"
        @handleCurrentChange="changePage"
        @handlePageSizeChange="handlePageSizeChange"
      />
    </div>
    <!-- 挂载资源弹窗 -->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="mountDialogVisible"
      title="选择资源进行挂载"
      width="1200px"
    >
      <!-- 1. 新增搜索条件区域 -->
      <div class="mount-search-container" style="margin-bottom: 15px;">
        <el-input
          v-model="mountQuery.resourceName"
          size="small"
          clearable
          placeholder="输入资源名称"
          style="width: 240px;"
          class="mount-filter-item"
          @keyup.enter.native="getMountResourceList"
        />
        <el-select
          v-model="mountQuery.resourceType"
          size="small"
          clearable
          placeholder="选择资源类型"
          disabled
          style="width: 160px;"
          class="mount-filter-item"
          @change="getMountResourceList"
        >
          <el-option label="API" value="0" />
          <el-option label="数据库" value="1" />
          <el-option label="文件" value="2" />
        </el-select>
        <!-- 1. 新增：请求方式筛选下拉框 -->
        <el-select
          v-model="mountQuery.resourceApiMethod"
          size="small"
          clearable
          placeholder="选择请求方式"
          style="width: 160px;"
          class="mount-filter-item"
          @change="getMountResourceList"
        >
          <el-option label="POST" value="0" /> <!-- 对应后端值0 -->
          <el-option label="GET" value="1" /> <!-- 对应后端值1 -->
        </el-select>
        <el-button size="small" type="primary" class="mount-filter-item" @click="getMountResourceList">
          搜索
        </el-button>
        <el-button size="small" class="mount-filter-item" @click="resetMountSearch">
          重置
        </el-button>
      </div>

      <!-- 2. 表格修改：删除type="selection"列，新增操作栏 -->
      <el-table
        ref="resourceTable"
        v-loading="mountLoading"
        highlight-current-row
        style="width: 100%;"
        :data="resourceList"
        border
        @selection-change="handleSelectionChange"
      >
        <!-- 添加单选复选框列 -->
        <el-table-column type="selection" width="55" :selectable="handleSelectable" />
        <el-table-column prop="resourceName" label="资源名称" width="200" />
        <el-table-column label="资源类型" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.resourceType === '0'">API</span>
            <span v-if="scope.row.resourceType === '1'">数据库</span>
            <span v-if="scope.row.resourceType === '2'">文件</span>
          </template>
        </el-table-column>
        <el-table-column prop="resourceSm" label="资源说明" show-overflow-tooltip />
        <el-table-column label="详细信息" width="300">
          <template slot-scope="scope">
            <div v-if="scope.row.resourceType === '0'">
              <div>URL: {{ scope.row.resourceApiUrl || '-' }}</div>
              <div>请求方式: {{ scope.row.resourceApiMethod === '0' ? 'POST' : 'GET' }}</div>
            </div>
            <div v-if="scope.row.resourceType === '1'">
              <div>文件格式: {{ scope.row.resourceFileType || '-' }}</div>
              <div>文件路径: {{ scope.row.resourceFilePath || '-' }}</div>
            </div>
            <div v-if="scope.row.resourceType === '2'">
              <div>类型: {{ scope.row.resourceDataType || '-' }}</div>
              <div>地址: {{ scope.row.resourceDataIp }}:{{ scope.row.resourceDataPort }}</div>
              <div>实例: {{ scope.row.resourceDataName || '-' }}</div>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 3. 新增分页组件 -->
      <div class="mount-pagination-container" style="margin-top: 15px; text-align: right;">
        <el-pagination
          background
          layout="prev, pager, next, total"
          :total="mountTotalCount"
          :page-size="mountPageSize"
          :current-page="displayPage"
          @current-change="handleMountPageChange"
        />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="mountDialogVisible = false">取消</el-button>
        <!-- 添加确认挂载按钮 -->
        <el-button type="primary" :disabled="selectedResources.length === 0" @click="confirmMount">
          确认挂载
        </el-button>
      </div>
    </el-dialog>
    <ZybmInfoDialog ref="detailsDialog" />
  </div>
</template>

<script>
import Pagination from '@/components/common/Pagination.vue'
import ZybmInfoDialog from './ZybmInfoDialog.vue'
import {
  getQuerySharingApp,
  getDataResource,
  getDataResourceMounting,
  getQuerySharingAppDtail,
  delDataResourceMounting,
  dataResourceMountingDelResource,
  getDataTypeGetallDept
} from '@/api/resource/application'

export default {
  name: 'ApplicationList',
  components: { ZybmInfoDialog, Pagination },
  data() {
    return {
      timeValue: [],
      mountDialogVisible: false,
      mountLoading: false,
      resourceList: [],
      currentRow: null, // 当前申请行数据
      // 3. 新增挂载弹窗搜索条件
      mountQuery: {
        resourceName: '', // 资源名称搜索
        resourceType: '', // 资源类型筛选
        resourceApiMethod: ''
      },
      // 4. 新增挂载弹窗分页参数（与文档2的page/size字段匹配）
      mountCurrentPage: 0, // 当前页码
      mountPageSize: 10, // 每页条数
      mountTotalCount: 0, // 资源总数
      selectedResources: [], // 选中的资源
      // 表格数据
      tableData: [],
      loading: false,
      totalCount: 0,
      currentPage: 1,
      pageSize: 10,

      // 查询条件
      query: {
        appNub: '',
        appDept: '',
        appApplicant: '',
        appName: '',
        catalogName: '',
        appStu: '',
        isMr: ''
      },

      form: {
        appNub: '',
        catalogName: '',
        appMethod: '',
        appMethodText: '',
        appDept: '',
        appName: '',
        appPhone: '',
        appEmail: '',
        appScenarios: '',
        appMatters: '',
        appBasis: '',
        appStu: '',
        appStuText: '',
        remarks: '',
        isOverdue: 0,
        isOverdueText: '',
        isMr: '',
        isMrText: ''
      },

      // 申请状态映射表
      statusMap: {
        '0': '待审批',
        '1': '数据局审批通过',
        '2': '审批通过',
        '3': '审批拒绝',
        '4': '已撤销',
        '5': '已删除'
      },

      // 状态样式映射
      statusTypeMap: {
        '0': 'warning', // 待审批-警告色
        '1': 'info', // 数据局审批通过-信息色
        '2': 'success', // 审批通过-成功色
        '3': 'danger', // 审批拒绝-危险色
        '4': 'gray', // 已撤销-灰色
        '5': 'danger' // 已撤销-灰色

      },

      appDeptOptions: []
    }
  },
  computed: {
    // 计算显示在分页组件上的页码（从1开始）
    displayPage() {
      return this.mountCurrentPage + 1
    }
  },
  created() {
    this.loadTableData()

    getDataTypeGetallDept().then(res => {
      console.log('下拉框', res)

      this.appDeptOptions = res.map(item => {
        return {
          label: item.name,
          value: item.id
        }
      })
    })
  },
  methods: {
    // 确认挂载逻辑
    confirmMount() {
      if (this.selectedResources.length === 0) return

      const resource = this.selectedResources[0]
      const params = {
        appNub: this.currentRow.appNub,
        resourceId: resource.id
      }

      // 调用挂载接口
      getDataResourceMounting(params).then(res => {
        console.log(res, '挂载成功')
        this.$message.success(`资源「${resource.resourceName}」挂载成功`)
        this.mountDialogVisible = false
        this.loadTableData()
      }).catch(err => {
        console.error('挂载失败', err)
        // this.$message({
        //   message: err.response.data.message,
        //   type: 'error'
        // })
      })
    },
    // 处理选择变化
    handleSelectionChange(selection) {
      // 始终只保留最后一个选中项（实现单选效果）
      if (selection.length > 1) {
        this.$refs.resourceTable.clearSelection()
        this.$refs.resourceTable.toggleRowSelection(selection[selection.length - 1], true)
        this.selectedResources = [selection[selection.length - 1]]
      } else {
        this.selectedResources = selection
      }
    },
    // 处理单选逻辑
    handleSelectable(row, index) {
      // 当已有选中项时，禁止选择其他项
      return this.selectedResources.length === 0 ||
        (this.selectedResources.length === 1 && this.selectedResources[0].id === row.id)
    },
    // 1. 修改挂载资源弹窗打开逻辑：初始化搜索和分页参数
    mountResource(row) {
      this.currentRow = row
      this.mountLoading = true
      // 初始化搜索条件和分页
      this.mountQuery = { resourceName: '', resourceType: this.currentRow.appMethod, resourceApiMethod: '' }
      this.mountCurrentPage = 0
      // 调用带搜索和分页的资源列表接口
      this.getMountResourceList()
    },

    // 2. 新增：获取挂载资源列表（带搜索和分页）
    getMountResourceList() {
      this.mountLoading = true
      // 调用接口时传递搜索条件和分页参数（与文档2的API参数匹配）
      getDataResource({
        page: this.mountCurrentPage,
        size: this.mountPageSize,
        resourceName: this.mountQuery.resourceName || null,
        resourceType: this.mountQuery.resourceType || null,
        resourceApiMethod: this.mountQuery.resourceApiMethod || null
      }).then(res => {
        console.log(res, '9999')
        this.resourceList = res.content // 资源列表数据
        this.mountTotalCount = res.totalElements // 资源总数（用于分页）
        this.mountLoading = false
        this.mountDialogVisible = true
      }).catch(err => {
        console.error('获取资源列表失败', err)
        this.mountLoading = false
      })
    },

    // 3. 新增：挂载弹窗分页切换
    handleMountPageChange(page) {
      // page是用户点击的显示页码（1,2,3...）
      const targetPage = page - 1 // 转换为后端需要的页码（0,1,2...）

      // 避免重复请求
      if (targetPage === this.mountCurrentPage) {
        return
      }

      this.mountCurrentPage = targetPage
      this.getMountResourceList()
    },

    // 4. 新增：重置挂载弹窗搜索条件
    resetMountSearch() {
      this.mountQuery = { resourceName: '', resourceType: '', resourceApiMethod: '' }
      this.mountCurrentPage = 0 // 重置页码为第一页
      this.getMountResourceList()
    },

    // 解除挂载资源方法（暂时简单定义，后续完善具体逻辑）
    unmountResource(row) {
      console.log(`执行解除挂载资源操作，对应申请编号：${row.appNub}`)
      // 这里可以添加实际的解除挂载资源的业务逻辑，比如调用接口等
      this.$confirm('确定要解除挂载资源吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          delDataResourceMounting({ appNub: row.appNub }).then(res => {
            console.log(res, '123')
            this.$message({
              message: res,
              type: 'success'
            })
            this.loadTableData()
          })
        })
        .catch(() => {
        })
    },
    handleDelete(row) {
      console.log(row)
      this.$confirm('确定要删除吗？删除后不可恢复！', '提示', {
        type: 'warning'
      })
        .then(() => {
          dataResourceMountingDelResource({ appNub: row.appNub }).then(res => {
            console.log(res, '123')
            this.$message({
              message: res,
              type: 'success'
            })
            this.loadTableData()
          }).catch((err) => {
            console.log(err)
          })
        })
    },
    // 获取状态文本
    getStatusText(status) {
      return this.statusMap[status] || '未知状态'
    },

    // 获取状态样式
    getStatusType(status) {
      return this.statusTypeMap[status] || 'default'
    },

    // 加载表格数据
    loadTableData() {
      this.loading = true
      getQuerySharingApp({
        page: this.currentPage,
        size: this.pageSize,
        appNub: this.query.appNub || null,
        catalogName: this.query.catalogName || null,
        appDept: this.query.appDept || null,
        appApplicant: this.query.appApplicant || null,
        appName: this.query.appName || null,
        appStu: this.query.appStu || null,
        isMr: this.query.isMr || null,
        startTime: this.timeValue ? this.timeValue[0] : null,
        endTime: this.timeValue ? this.timeValue[1] : null
      }).then(res => {
        this.tableData = res.content
        this.totalCount = res.totalElements
        this.loading = false
      })
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.loadTableData()
    },

    // 重置搜索
    resetSearch() {
      this.query = {
        appNub: '',
        appDept: '',
        appApplicant: '',
        appName: '',
        catalogName: '',
        appStu: '',
        isMr: ''
      }
      this.timeValue = null

      this.handleSearch()
    },

    // 切换分页
    changePage(page) {
      this.currentPage = page
      this.loadTableData()
    },
    handlePageSizeChange(pageSize) {
      this.pageSize = pageSize
      this.currentPage = 1
      this.loadTableData()
    },
    // 打开详情弹窗
    openDetailDialog(row) {
      getQuerySharingAppDtail({ appNub: row.appNub }).then(res => {
        console.log(res.catalogInfoVo, '编目详情')
        console.log(res.sharingApp, '申请详情')
        console.log(res.dataResources, '资源挂载')
        this.$refs.detailsDialog.setDetailData(JSON.parse(res.catalogInfoVo))
        this.$refs.detailsDialog.setSharingAppData(
          JSON.parse(res.sharingApp),
          JSON.parse(res.dataResources || '{}') // 传递资源数据
        )
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// 弹窗样式
.detail-dialog {
  ::v-deep .el-dialog__body {
    padding: 15px 20px;
    max-height: 70vh;
    overflow-y: auto;
  }
}

// 表单样式
.detail-form {
  width: 100%;
}

// 表单分区样式
.form-section {
  margin-bottom: 18px;
  padding: 12px 15px;
  background-color: #ffffff;
  border-radius: 6px;
  border: 1px solid #f1f5f9;
}

.section-title {
  margin: 0 0 12px 0;
  font-size: 13px;
  color: #1e40af;
  font-weight: 500;
  padding-bottom: 8px;
  border-bottom: 1px dashed #dbeafe;
}

// 一行两列网格布局
.form-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 15px; // 列之间的间距
}

// 表单项样式
.form-item {
  flex: 1; // 自动分配宽度，实现一行两列
  min-width: 280px; // 最小宽度，避免过窄
  margin-bottom: 8px !important;

  &.full-width {
    flex: 0 0 100%; // 占满整行
  }

  .el-form-item__label {
    color: #475569;
    font-size: 12px;
    padding-right: 10px;
    line-height: 1.5;
  }

  .el-form-item__content {
    line-height: 1.5;
  }
}

// 输入框样式
.form-input {
  width: 100% !important;
  border-radius: 4px;
  font-size: 12px;
  height: 32px;

  &:disabled {
    background-color: #f8fafc;
    color: #64748b;
    border-color: #e2e8f0;
  }

  &.el-textarea {
    height: auto !important;
  }
}

// 公共样式
.app-container {
  padding: 20px;
}

.filter-item {
  margin-right: 10px;
}

.role-span {
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

::v-deep .el-card__body {
  padding: 0 10px;
}

// 状态标签样式
::v-deep .el-tag {
  padding: 0 8px;
  height: 22px;
  line-height: 22px;
  font-size: 12px;
}

// 文本样式
.text-success {
  color: #0bbd87;
}

.text-danger {
  color: #ff4d4f;
}

.text-info {
  color: #1890ff;
}
</style>
